/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { defineComponent, PropType, reactive, ref, VNode, watch } from 'vue';
import { IDEDRBar } from '@ibiz/model-core';
// import { useRoute, useRouter } from 'vue-router';
import {
  ControllerEvent,
  EventBase,
  IControlProvider,
  IDRBarItemsState,
  IViewEvent,
} from '@ibiz-template/runtime';
import { DRBarAnchorStyleController } from './drbar-anchor-style.controller';
import './drbar-anchor-style.scss';
import { resource } from '../global';

export const DRBarAnchorStyleControl = defineComponent({
  name: 'IBizDRBarAnchorStyle',
  props: {
    modelData: { type: Object as PropType<IDEDRBar>, required: true },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    provider: { type: Object as PropType<IControlProvider> },
    srfnav: { type: String, required: false },
    showMode: { type: String, default: 'vertical' },
    hideEditItem: { type: Boolean, default: undefined },
  },
  setup(props) {
    const c = useControlController(
      (...args) => new DRBarAnchorStyleController(...args),
    );
    const ns = useNamespace('drbar-anchor-style');
    // const router = useRouter();

    const isCollapse = ref(false);

    const counterData = reactive<IData>({});
    c.evt.on('onCreated', () => {
      if (c.counter) {
        c.counter.onChange((counter: IData) => {
          Object.assign(counterData, counter);
        }, true);
      }
    });

    // c.setRouter(router);

    const handleSelect = (key: string): void => {
      c.handleSelectChange(key);
    };

    // const route = useRoute();

    // let expViewRoutePath = '';

    const opens: string[] = [];

    watch(
      () => c.state.isCreated,
      (_newVal, _oldVal) => {
        if (props.showMode !== 'horizontal') {
          const { drBarItems } = c.state;
          drBarItems.forEach(item => {
            opens.push(item.tag);
          });
        }
      },
    );

    // if (c.routeDepth) {
    //   expViewRoutePath = getNestedRoutePath(route, c.routeDepth);
    // }

    // watch(
    //   () => route.fullPath,
    //   (newVal, oldVal) => {
    //     if (newVal !== oldVal) {
    //       const depth = c.routeDepth;
    //       if (depth) {
    //         const currentRoutePath = getNestedRoutePath(route, c.routeDepth);
    //         if (currentRoutePath === expViewRoutePath) {
    //           const routePath = route2routePath(route);
    //           const { srfnav } = routePath.pathNodes[depth! - 1];
    //           c.handleSelectChange(srfnav);
    //         }
    //       }
    //     }
    //   },
    //   { immediate: true },
    // );

    const renderMenuItems = (item: IDRBarItemsState): VNode | undefined => {
      if (!item.visible) {
        return;
      }
      if (item.children) {
        let subtitle = '';

        // 水平显示的时候，父菜单标题同时显示子菜单选中的子标题
        if (props.showMode === 'horizontal') {
          if (item.tag !== c.state.selectedItem) {
            const find = item.children.find(
              x => x.tag === c.state.selectedItem,
            );
            if (find) {
              subtitle = `-${find.caption}`;
            }
          }
        }
        return (
          <el-sub-menu
            class={ns.b('group')}
            index={item.tag}
            disabled={item.disabled}
          >
            {{
              default: () =>
                item.children!.map(child => {
                  return renderMenuItems(child);
                }),
              title: () => [
                <iBizIcon class={ns.e('icon')} icon={item.sysImage}></iBizIcon>,
                <span>
                  {item.caption}
                  {subtitle}
                </span>,
              ],
            }}
          </el-sub-menu>
        );
      }
      return (
        <el-menu-item
          class={ns.e('item')}
          index={item.tag}
          disabled={item.disabled}
        >
          <iBizIcon class={ns.e('icon')} icon={item.sysImage}></iBizIcon>
          <span>{item.caption}</span>
          {item.counterId && counterData[item.counterId] && (
            <iBizBadge
              class={ns.e('counter')}
              value={counterData[item.counterId]}
            />
          )}
        </el-menu-item>
      );
    };

    const shrinkClick = (): void => {
      isCollapse.value = !isCollapse.value;
      (
        c.view.evt as ControllerEvent<
          IViewEvent & {
            onClickShrink: {
              event: EventBase;
              emitArgs: IData;
            };
          }
        >
      ).emit('onClickShrink', { shrink: isCollapse.value });
    };

    return {
      c,
      ns,
      handleSelect,
      renderMenuItems,
      opens,
      shrinkClick,
      isCollapse,
    };
  },
  render() {
    const { isCreated, drBarItems, selectedItem } = this.c.state;
    return (
      <div
        class={[this.ns.e('wrapper'), this.isCollapse ? 'isCollapse' : '']}
        style='position: relative;'
      >
        <span
          class={[this.ns.e('icon'), this.isCollapse ? 'isCollapse' : '']}
          style={{
            backgroundImage: `url(${resource.dir('assets/svg/svg.svg')})`,
          }}
          onClick={this.shrinkClick}
        ></span>
        <iBizControlBase
          controller={this.c}
          class={[this.ns.b(), this.isCollapse ? 'isCollapse' : '']}
        >
          {isCreated && (
            <el-menu
              class={this.ns.e('menu')}
              mode={this.showMode}
              default-active={selectedItem}
              onSelect={this.handleSelect}
              default-openeds={this.opens}
            >
              {drBarItems.map(item => {
                return this.renderMenuItems(item);
              })}
            </el-menu>
          )}
        </iBizControlBase>
      </div>
    );
  },
});
